﻿using IdentityService.Infrastructure;
using MediatR;

namespace IdentityService.Application.Behaviours
{
    public class TransactionBehaviour<TRequest, TResponse> : IPipelineBehavior<TRequest, TResponse> where TRequest : IRequest<TResponse>
    {
        private readonly AppIdentityDbContext _dbContext;
        public TransactionBehaviour(AppIdentityDbContext dbContext) => _dbContext = dbContext;

        public async Task<TResponse> Handle(TRequest request, RequestHandlerDelegate<TResponse> next, CancellationToken cancellationToken)
        {
            using var transaction = _dbContext.Database.BeginTransaction();
            
            var response = await next();

            await _dbContext.SaveEntitiesAsync(cancellationToken);

            try { transaction.Commit(); }
            catch (Exception ex) 
            { 
                transaction.Rollback(); 
            }
            finally { transaction.Dispose(); }
            
            return response;
        }
    }
}
